package com.itop.automator.commom;


import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;

public class IOUtils {
    private static final String TAG = "IOUtils";

    public static void closeQuietly(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException e) {
                Logger.e(TAG, e.getMessage());
            }
        }
    }

    public static void closeQuietly(Socket socket) {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                Logger.e(TAG, e.getMessage());
            }
        }
    }

    public static void closeQuietly(ServerSocket socket) {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                Logger.e(TAG, e.getMessage());
            }
        }
    }

    public static byte[] toByteArray(InputStream is) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        copy(is, bos);
        bos.close();
        return bos.toByteArray();
    }

    public static void copy(InputStream is, OutputStream os) throws IOException {
        byte[] data = new byte[2048];
        int read = 0;
        while ((read = is.read(data)) >= 0) {
            os.write(data, 0, read);
        }
    }

    public static int readFully(InputStream is, byte[] buf) throws IOException {
        return readFully(is, buf, 0, buf.length);
    }

    public static int readFully(InputStream is, byte[] buf, int offset, int len) throws IOException {
        int i = 0;
        for (; i < len; ++i) {
            int c = is.read();
            if (c == -1) {
                break;
            }
            buf[i + offset] = (byte) c;
        }
        return i;
    }

    public static String toStringQuietly(byte[] buf) {
        try {
            return new String(buf, Constants.UTF_8);
        } catch (UnsupportedEncodingException e) {
            Logger.e(TAG, e.getMessage());
            return null;
        }
    }

    public static byte[] toByteArrayQuietly(String value) {
        try {
            return value.getBytes(Constants.UTF_8);
        } catch (UnsupportedEncodingException e) {
            Logger.e(TAG, e.getMessage());
            return new byte[0];
        }
    }

    public static int readUnsignedShort(byte[] buf, int offset) {
        return ((buf[offset] & 0xff) << 8) + (buf[offset + 1] & 0xff);
    }
}

